<?php
/**
 * Short Description  
 *
 * Long Description 
 *
 * @copyright 
 * @version   $Id: AclDAO.php 12 2011-04-09 08:58:51Z sandeep.manne@gmail.com $
 */

require_once 'Core/DAO.php';

class AclDAO extends Core_DAO
{
	protected $_name        = 'acl';
	protected $_primary 	= 'acl_id';
	
	const GRANTED     = 0;
	const DENIED      = 1;     
	
	public function addAcl($groupId, $module, $controller, $action, $permission)
	{
		
		$aclDetails = array("group_id"      => $groupId,
							"resource_name" => $this->_getResourceName($module, $controller, $action),
							"permission"    => $permission,
							"status"        => 1);
		return $this->insert($aclDetails);
	}
	
	private function _getResourceName($module, $controller, $action)
	{
		if ($action) {
			return $module."_".$controller."_".$action;
		} else if ($controller) {
			return $module."_".$controller;
		} else {
			return $module;
		}
	}
	
	public function updateAcl($resourceId, $groupId, $permission)
	{
		$where = $this->getDefaultAdapter()
                      ->quoteInto('resource_id = ? AND group_id = ?', array($resourceId, $groupId));
		
		$result = $this->updateData(array("permission" => $permission), $where);	
		
		return $result;
	}
	
	public function getAclByGroupId($groupId)
	{
		return $this->select()
					->from($this->_name)
					->where("group_id = ?", $groupId)
					->query()
					->fetchAll();
	}
	
	/**
	 * Return acl for given resource
	 * 
	 * @param string $module
	 * @param string $controller
	 * @param string $action
	 */
	public function getAclByResource($module, $controller, $action)
	{
		return $this->select()
					->from($this->_name)
					->where("resource_name like ?", $this->_getResourceName($module, $controller, $action))
					->query()
					->fetchAll();
	}
	
	public function isAllowed($gId, $module, $controller, $action)
    {
        $result = $this->select()
        			   ->from($this->_name)
        			   ->where("resource_name = ?", $module."_".$controller."_".$action)
        			   ->orWhere("resource_name = ?", $module."_".$controller)
        			   ->orWhere("resource_name = ?", $module)
        			   ->limit(1)
        			   ->query()
        			   ->fetchAll();
        			   
        return count($result) == 0;
    }
}